/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yuanma.android.boan;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.content.SharedPreferences;
import android.content.Context;
import android.os.AsyncTask;

//import org.apache.http.HttpStatus;
import org.json.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;

import android.util.Log;

/**
 * This sample demonstrates cross-fading between two overlapping views.
 *
 * <p>In this sample, the two overlapping views are a loading indicator and some text content. The
 * active view is toggled by touching the toggle button in the action bar. In real-world
 * applications, this toggle would occur as soon as content was available. Note that if content is
 * immediately available, a loading spinner shouldn't be presented and there should be no
 * animation.</p>
 */
public class LoginActivity extends Activity {


    static public String loginName="";
    static public String userName="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		    
        setContentView(R.layout.activity_login);
	EditText sgzText = (EditText) findViewById(R.id.login_name);
	if(JsonPullService.loginName.length()>0)
	    sgzText.setText(JsonPullService.loginName);
	
	Button loginButton = (Button) findViewById(R.id.btnLogin);
 
        loginButton.setOnClickListener(new View.OnClickListener() {
 
		public void onClick(View v) {
	
		    EditText sgzText = (EditText) findViewById(R.id.login_name);
		    EditText pwdText = (EditText) findViewById(R.id.login_password);
		    String localUrlString=String.format("http://%s:%s/boan/jsonLogin.brl?loginName=%s&password=%s",
							Constants.WEB_SERVER_IP,Constants.WEB_SERVER_PORT,
							sgzText.getText().toString(),pwdText.getText().toString());
	
		    new LoginTask().execute(localUrlString);
	
		
		}
        });

    }
  

    private class LoginTask extends AsyncTask<String, Void, String> {
	
        @Override
	    protected String doInBackground(String... urls) {
	    String result=getString(R.string.http_code_error);
	    
	    try {
		HttpURLConnection localHttpURLConnection = (HttpURLConnection) (new URL(urls[0]).openConnection());
		localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);
		int responseCode = localHttpURLConnection.getResponseCode();
		switch (responseCode) {
		case HttpURLConnection.HTTP_OK:
		    String jsnString= Utility.fromStream(localHttpURLConnection.getInputStream());

		    JSONTokener jsonParser = new JSONTokener(jsnString);
		    JSONObject userInfo= (JSONObject)jsonParser.nextValue();
		    if(userInfo.isNull("sgzh")) 
			result=getString(R.string.message_login_error);
		    else {
			 loginName = userInfo.getString("sgzh");
			 userName = userInfo.getString("driver_name");
		    }
		    result="ok";
		    
		    break;
		}
		// Handles possible exceptions
	    } catch (MalformedURLException localMalformedURLException) {

		result= localMalformedURLException.getMessage();

	    } catch (IOException localIOException) {
		result =localIOException.getMessage();
	    } catch (JSONException localJsonException) {
		result = localJsonException.getMessage();
	    } catch (ClassCastException localCastException) {
		//result = localJsonException.getMessage();
		result=getString(R.string.message_login_error);

	    } finally {
		if (Constants.LOGD) {
		    
		    Log.d("LoginActivity", new String("loginJson:").concat(urls[0]));
		}

	    }
	    return result;
	    
        }
 
        /**
         * Uses the logging framework to display the output of the fetch
         * operation in the log fragment.
         */
        @Override
	    protected void onPostExecute(String result) {
	    
	    
	    if(result.compareTo("ok")==0){
		
		startService(new Intent(LoginActivity.this, JsonPullService.class).addCategory("After_Login"));
		//startActivity(new Intent(Utility.mainActivity, MainActivity.class));
	    }else{
		TextView hintView = (TextView) findViewById(R.id.login_hint);
		hintView.setText(result);
		
	    }
	    
		
        }
    }
}
